package Dao.MsgAndEmail.Imp;

import Dao.MsgAndEmail.MessageDao;

import Entity.MsgAndEmail.Message;
import Util.DBUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class MessageDaoImp implements MessageDao {
    private PreparedStatement ps = null;
    private ResultSet rs = null;

    @Override
    public List<Message> getAllMessage(String queryKey, Integer offset, Integer limit, Connection conn) {
        List<Message> messages = new ArrayList<>();
        try {
            String sql = "select  msg_id, msg_title, msg_content, msg_from, msg_time, msg_filename, msg_filepath, msg_to " +
                    "from message where msg_title like ? limit ?,?";
            ps = conn.prepareStatement(sql);
            ps.setString(1, queryKey);
            ps.setInt(2, offset);
            ps.setInt(3, limit);
            rs = ps.executeQuery();
            while (rs.next()) {
                Integer msgId = rs.getInt("msg_id");
                String msgTitle = rs.getString("msg_title");
                String msgContent = rs.getString("msg_content");
                String msgFrom = rs.getString("msg_from");
                String msgTime = rs.getString("msg_time");
                String msgFilename = rs.getString("msg_filename");
                String msgFilepath = rs.getString("msg_filepath");
                String msgTo = rs.getString("msg_to");
                Message message = new Message(msgId, msgTitle, msgContent, msgFrom, msgTime, msgFilename, msgFilepath, msgTo);
                messages.add(message);
            }
        } catch (SQLException e) {
            e.printStackTrace();
            return messages;
        } finally {
            DBUtil.closeMySQLResource(ps, rs);
        }
        return messages;
    }

    @Override
    public Integer updateFile(Integer id, String fileName, String url, Connection conn) {
        int res = 0;

        String sql = "update message set msg_filename = ?, msg_filepath = ? where msg_id = ?";
        try {
            ps = conn.prepareStatement(sql);
            ps.setString(1, fileName);
            ps.setString(2, url);
            ps.setInt(3, id);
            res = ps.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.closeMySQLResource(ps, rs);
        }
        return res;
    }
}
